package com.itsoku.chat34;

import lombok.Getter;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * DelayQueue延迟队列中存放的对象，必须是实现Delayed接口的类对象。
 * Delayed接口，是Comparable的子类：
 */
public class TaskInfo implements Delayed {
    //任务id  
    private int id;  
    //业务类型  
    private int type;  
    //业务数据  
    private String data;  
    //执行时间  
    private long excuteTime;

    public TaskInfo(int id, int type, String data, long excuteTime) {  
        this.id = id;  
        this.type = type;  
        this.data = data;
        // 将到期时间转为纳秒后，再加上当前时间的时间戳
        this.excuteTime = TimeUnit.NANOSECONDS.convert(excuteTime, TimeUnit.MILLISECONDS) + System.nanoTime();
    }

    public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    public int getType() {  
        return type;  
    }  
    public void setType(int type) {  
        this.type = type;  
    }  
    public String getData() {  
        return data;  
    }  
    public void setData(String data) {  
        this.data = data;  
    }  
    public long getExcuteTime() {  
        return excuteTime;  
    }  
    public void setExcuteTime(long excuteTime) {  
        this.excuteTime = excuteTime;  
    }

    /**
     * 通过DelayQueue的take方法获取对象时，会调用对象的getDelay方法，确定延迟获取时间，
     * 需要注意的是这里的时间单位为纳秒
     *
     * 计算剩余时间，并转为纳秒
     */
    @Override  
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.excuteTime - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override  
    public int compareTo(Delayed o) {  
        TaskInfo msg = (TaskInfo)o;
        return this.excuteTime > msg.excuteTime ? 1 : (this.excuteTime < msg.excuteTime ? -1 : 0);
    }  
}